package com.myfojing.mycloud;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.PopupMenu;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ListView;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;

import io.realm.Realm;
import io.realm.RealmResults;


public class MainActivity extends AppCompatActivity {
    // activity 结果
    final static int DEVICE_EDIT = 0;
    final static int DEVICE_ADD = 1;
    final static int CONFIG_EDIT = 2;
    final private String TAG = "我的Main调试";
    // ui
    ListView listView;
    MainListviewAdapter adapter;
    Handler handler = new Handler();
    private DataService.DataBinder binder;
    private boolean isBound = false;
    private ArrayList<Sensirion> list = new ArrayList<>();
    // database
    private Realm realm;
    // 按钮监听
    private View.OnClickListener onCURDClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            pop_menu(v);
        }
    };
    // 接收本地广播
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            String mac = bundle.getString("mac");
            float t = bundle.getFloat("t");
            float h = bundle.getFloat("h");
            Log.d(TAG, String.format("接收到广播:%s,%2.1f,%2.1f%%", mac, t, h));
            for (int i = 0; i < list.size(); i++) {
                Sensirion sensirion = list.get(i);
                if (sensirion.getMac().equals(mac)) {
                    sensirion.setTemp(t);
                    sensirion.setHum(h);
                    break;
                }
                adapter.notifyDataSetChanged();
            }
            handler.post(new Runnable() {
                @Override
                public void run() {
                    adapter.notifyDataSetChanged();
                }
            });
        }
    };

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (DataService.DataBinder) service;
            isBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case CONFIG_EDIT:
                if (resultCode == RESULT_OK) {
                    // 修改服务的操作间隔
                    binder.change_interval(data.getIntExtra("in1", 1), data.getIntExtra("in2", 1));
                }
                break;
            case DEVICE_ADD:
            case DEVICE_EDIT:
                if (resultCode == RESULT_OK) {
                    // 服务重新读数据
                    binder.refresh();
                    // 刷新listview
                    get_device();
                    adapter.notifyDataSetChanged();
                }

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // ui
        listView = (ListView) findViewById(R.id.main_listview);
        listView.addHeaderView(getLayoutInflater().inflate(R.layout.main_listview_header, null));

        adapter = new MainListviewAdapter(this, list, onCURDClickListener);
        listView.setAdapter(adapter);
        // data
        realm = Realm.getDefaultInstance();
        get_device();
    }

    // 恢复
    @Override
    protected void onResume() {
        //Log.d(TAG, "主onResume()");
        // 检查服务
        checkService();
        // 绑定服务
        if (!isBound) {
            Intent intent = new Intent(this, DataService.class);
            bindService(intent, connection, BIND_AUTO_CREATE);
        }
        // 注册广播
        LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(
                receiver, new IntentFilter("event_rh"));
        super.onResume();
    }

    @Override
    protected void onPause() {
        //Log.d(TAG, "主onPause()");
        // 反注册服务
        if (isBound) {
            unbindService(connection);
            isBound = false;
        }
        // 反注册广播
        LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(receiver);
        super.onPause();
    }

    @Override
    protected void onStop() {
        //Log.d(TAG, "主onStop()");
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        //Log.d(TAG, "主onDestroy()");
        realm.close();
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    /* 菜单 */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent;
        switch (item.getItemId()) {
/*            // 网络
            case R.id.m_network:
                intent = new Intent(MainActivity.this, ConfigNetworkActivity.class);
                startActivity(intent);
                break;*/

            // 添加节点：手动
            case R.id.m_manual_add:
                intent = new Intent(MainActivity.this, AddActivity.class);
                startActivity(intent);
                break;

            // 添加节点：扫描
            case R.id.m_scan_add:
                intent = new Intent(MainActivity.this, DiscoveryActivity.class);
                startActivityForResult(intent, DEVICE_ADD);
                break;

            // 设置
            case R.id.m_setting:
                intent = new Intent(MainActivity.this, SettingActivity.class);
                startActivityForResult(intent, CONFIG_EDIT);
        }
        return true;
    }

    /* 自定义函数 */

    // pop 菜单
    private void pop_menu(View v) {
        // 菜单
        ImageButton button = (ImageButton) v.findViewById(R.id.sensirion_curd);
        final int pos = (Integer) button.getTag();
        final Sensirion model = list.get(pos);

        PopupMenu popupMenu = new PopupMenu(MainActivity.this, button);
        popupMenu.getMenuInflater().inflate(R.menu.popup_main, popupMenu.getMenu());
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.pop_main_del:
                        // 删除记录
                        AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);
                        dialog.setTitle("确认");
                        dialog.setMessage(String.format(Locale.CHINA, "%s:%s", "确认删除吗？", model.getTitle()));
                        // 确定
                        dialog.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                SensirionHelper.delete_sensirion(model.getMac(), realm);
                                refresh_list();
                                //
                                dialog.dismiss();
                            }
                        });
                        // 取消
                        dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        dialog.create().show();
                        break;
                    case R.id.pop_main_edit:
                        if (model != null) {
                            Intent intent = new Intent(MainActivity.this, ConfigActivity.class);
                            intent.putExtra("sensirion", model);
                            intent.putExtra("ip_config", model.getIp());
                            intent.putExtra("port_config", model.getPort());
                            startActivity(intent);
                        }
                        break;
                    case R.id.pop_main_more:
                        Intent intent = new Intent(MainActivity.this, MoreActivity.class);
                        intent.putExtra("model", model);
                        startActivity(intent);
                        break;
                }  // switch
                return false;
            }
        });
        popupMenu.show();
        // function end
    }

    // 刷新列表
    private void refresh_list() {
        get_device();
        adapter.notifyDataSetChanged();
        if (isBound) {
            binder.refresh();
        }
    }

    // 检查服务是否运行
    private void checkService() {
        boolean running = false;
        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo serviceInfo : manager.getRunningServices(Integer.MAX_VALUE)) {
            if ("com.myfojing.mycloud.DataService".equals(serviceInfo.service.getClassName())) {
                running = true;
                break;
            }
        }  // for

        boolean enabled = getSharedPreferences("profile", MODE_PRIVATE)
                .getBoolean("sample_service_enabled", true);
        if (enabled && !running) {
            startService(new Intent(this, DataService.class));
        }
        if (!enabled && running) {
            stopService(new Intent(this, DataService.class));
            Log.d(TAG, "停止服务");
        }

    }

    // 取设备
    private void get_device() {
        list.clear();
        RealmResults<Sensirion> mySensirions = SensirionHelper.get_all(realm);
        for (int i = 0; i < mySensirions.size(); i++) {
            Sensirion mySensirion = mySensirions.get(i);
            list.add(mySensirion);
        }
    }

    // 取CPU核数
    private int getNumberOfCores() {
        if (Build.VERSION.SDK_INT >= 17) {
            return Runtime.getRuntime().availableProcessors();
        } else {
            return getNumCoresOldPhones();
        }
    }

    private int getNumCoresOldPhones() {
        class CpuFilter implements FileFilter {
            @Override
            public boolean accept(File pathname) {
                //Check if filename is "cpu", followed by a single digit number
                if (Pattern.matches("cpu[0-9]+", pathname.getName())) {
                    return true;
                }
                return false;
            }
        }

        try {
            //Get directory containing CPU info
            File dir = new File("/sys/devices/system/cpu/");
            //Filter to only list the devices we care about
            File[] files = dir.listFiles(new CpuFilter());
            //Return the number of cores (virtual CPU devices)
            return files.length;
        } catch (Exception e) {
            //Default to return 1 core
            return 1;
        }
    }

    // end
}
